package com.buercorp.wangyu.core1.ch12.threads;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition和Lock可以配合使用来实现线程的等待和唤醒。
 * Condition接口提供了await()、signal()和signalAll()等方法，用于线程之间的协调和通信。
 * @author liyiyu
 */
public class ThreadTest8 {

        private Lock lock = new ReentrantLock();
        private Condition condition = lock.newCondition();

        public void method1() {
            try {
                lock.lock();
                /* some condition */
                while (true) {
                    condition.await();
                }
                // do something
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void method2() {
            try {
                lock.lock();
                // change the condition
                condition.signalAll();
            } finally {
                lock.unlock();
            }
        }
    }


